<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="产品编号" prop="productNumber">
				<el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable maxlength="200" show-word-limit @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable maxlength="200" show-word-limit @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['packageRecords:deliver:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['packageRecords:deliver:remove']">删除</el-button>
			</el-col>
			<CreateForm :ids="ids" formtype="t_packRecords1" />
			<right-toolbar menuNames="delivers74" :showSearch.sync="showSearch" @queryTable="getList" @changeTableData="changeTableData" :columns.sync="columns" perm="packageRecords:deliver:list"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<el-table ref="table" @row-click="row_click" v-loading="loading" :data="configList" @selection-change="handleSelectionChange" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column type="index" width="55" align="center" label="序号" />
				<el-table-column label="产品编号" prop="productNumber" :show-overflow-tooltip="true" min-width="150" v-if="columns[0].visible" />
				<el-table-column label="产品型号" prop="productModel" :show-overflow-tooltip="true" min-width="150" v-if="columns[1].visible" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleChecked(scope.row)" v-hasPermi="['packageRecords:deliver:checked']">发货检查</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['packageRecords:deliver:remove']">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination menuNames="Paginationdeliver" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
		<!-- 添加或修改参数配置对话框 -->
		<el-dialog title="添加发货产品" :visible.sync="open" width="1500px" append-to-body v-dialogDrag>
			<div class="userDialog">
				<div class="userLeft">
					<el-form :model="queryProcuct" ref="queryProcuct" size="small" :inline="true">
						<el-form-item label="记录名称" prop="recordName">
							<el-input clearable style="width: 200px" v-model="queryProcuct.recordName" placeholder="请输入产品名称" maxlength="200" show-word-limit />
						</el-form-item>
						<el-form-item label="产品编号" prop="productNumber">
							<el-input clearable style="width: 200px" v-model="queryProcuct.productNumber" placeholder="请输入产品编号" maxlength="200" show-word-limit />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryUser">搜索</el-button>
							<el-button icon="el-icon-refresh" size="mini" @click="resetQueryUser">重置</el-button>
						</el-form-item>
					</el-form>
					<el-table height="488px" v-loading="productloading" :data="productList" @selection-change="handleSelectionProduct" ref="multipleTable">
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column type="index" width="55" align="center" label="序号" />
						<el-table-column label="记录名称" prop="recordName" :show-overflow-tooltip="true" />
						<el-table-column label="产品编号" prop="productNumber" :show-overflow-tooltip="true" />
					</el-table>
					<pagination :total="productTotal" :page.sync="queryProcuct.pageNum" :limit.sync="queryProcuct.pageSize" @pagination="getrepairProductList" />
				</div>
				<div class="userCenter">
					<div @click="setRight"><i class="el-icon-right"></i></div>
					<div @click="setLeft"><i class="el-icon-back"></i></div>
				</div>
				<div class="userRight">
					<el-table :data="selectProductList" height="488px" ref="rightTable" @selection-change="handleBackUser" border>
						<el-table-column type="selection" width="55" align="center" />
						<el-table-column type="index" width="55" align="center" label="序号" />
						<el-table-column label="记录名称" prop="recordName" :show-overflow-tooltip="true" />
						<el-table-column label="产品编号" prop="productNumber" :show-overflow-tooltip="true" />
					</el-table>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="发货检查" :visible.sync="checkedopen" width="900px" append-to-body v-dialogDrag>
			<el-form ref="formcheck" :model="formcheck" label-width="100px" :rules="rules">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="包装操作者" prop="packagUserId">
							<el-select v-model="formcheck.packagUserId" @change="selectpackagUser">
								<el-option v-for="item in workLists" :key="item.userId" :value="item.userId" :label="item.nickName"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="检验员" prop="checkoutUserId">
							<el-select v-model="formcheck.checkoutUserId" @change="selectcheckoutUser">
								<el-option v-for="item in userlist" :key="item.userId" :value="item.userId" :label="item.nickName"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div>
				<div class="onerow">
					<div>产品名称</div>
					<div>
						<el-tooltip class="item" effect="dark" :content="formcheck.productName" placement="top-start">
							<el-input style="width: 130px" v-model="formcheck.productName"></el-input>
						</el-tooltip>
					</div>
					<div>产品型号</div>
					<div style="border-right: 1px solid">
						<el-tooltip class="item" effect="dark" :content="formcheck.productModel" placement="top-start">
							<el-input style="width: 130px" v-model="formcheck.productModel"></el-input>
						</el-tooltip>
					</div>
				</div>
				<div class="onerow">
					<div style="border-top: none">产品数量</div>
					<div style="border-top: none"><el-input style="width: 130px" v-model="formcheck.productQuantity"></el-input></div>
					<div style="border-top: none">任务单编号</div>
					<div style="border-right: 1px solid; border-top: none">
						<el-tooltip class="item" effect="dark" :content="formcheck.productNumber" placement="top-start">
							<el-input style="width: 130px" v-model="formcheck.productNumber"></el-input>
						</el-tooltip>
					</div>
				</div>
				<div class="onerow">
					<div style="border-top: none">封装数量</div>
					<div style="border-top: none"><el-input style="width: 130px" v-model="formcheck.boxOneQuantity"></el-input>箱</div>
					<div style="border-top: none"><el-input style="width: 50px" v-model="formcheck.boxTwoQuantity"></el-input>箱 <el-input style="width: 60px" v-model="formcheck.pieceOneQuantity"></el-input>件</div>
					<div style="border-right: 1px solid; border-top: none"><el-input style="width: 130px" v-model="formcheck.pieceTwoQuantity"></el-input>件</div>
				</div>
			</div>
			<div style="height: 52vh; overflow-y: auto; margin-top: 10px">
				<el-table v-loading="checkedloading" :data="formcheck.tdeliverResultList" border>
					<!-- <el-table-column type="selection" width="55" align="center" /> -->
					<el-table-column type="index" width="55" align="center" label="序号" />
					<el-table-column label="检查内容" prop="deliverType" :show-overflow-tooltip="true" :formatter="getcontentcheck" min-width="180" />
					<el-table-column label="检查结果" align="center" prop="deliverResult" :show-overflow-tooltip="true" min-width="180">
						<template slot-scope="scope">
							<el-input v-model="scope.row.deliverResult" maxlength="50" show-word-limit></el-input>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="cacheFormChecked">暂 存</el-button>
				<el-button type="primary" @click="submitFormChecked">确 定</el-button>
				<el-button @click="checkedopen = false">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import CreateForm from "@/views/components/CreateForm"
import { getcolumn,allocatedList } from "@/api/selectList"
import { mapGetters } from "vuex"
import { deliverdelete, deliverinstallDeliver, detailIds, generateDeliver, deliverList1, userDown, getpackag, workerList, repairProductList, installDeliver, generatePackage, detailsEdits, detailsEdit, detailList, getdeliver, packagdelete, packagedit, deliverList } from "@/api/packageRecords"
export default {
	name: "Deliver",
	dicts: ["army_state"],
	components: { CreateForm },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			// 列信息
			columns: [
				// { key: 0, label: `记录编号`, visible: true },
				{ key: 0, label: `产品编号`, visible: true },
				{ key: 1, label: `产品型号`, visible: true }
			],
			BackSelectionProcuct: [],
			selectProductList: [],
			queryProcuct: {
				pageNum: 1,
				pageSize: 10,
				recordName: undefined,
				productNumber: undefined
			},
			productTotal: 0,
			titles1: "",
			eleTabTop: 0, //表格容器距浏览器顶部距离
			rules: {
				packagUserId: [{ required: true, message: "包装操作者不能为空", trigger: "blur" }],
				checkoutUserId: [{ required: true, message: "检验员不能为空", trigger: "blur" }]
			},
			userlist: [],
			formcheck: {
				packagUserId: undefined,
				checkoutUserId: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined,
				repairNumber: undefined,
				boxOneQuantity: undefined,
				boxTwoQuantity: undefined,
				pieceTwoQuantity: undefined,
				tdeliverResultList: undefined
			},
			checkedopen: false,
			checkedloading: false,
			workLists: [],
			checkContentList: [
				{
					id: "1",
					name: "包装箱规格符合工艺规程要求"
				},
				{
					id: "2",
					name: "无损伤"
				},
				{
					id: "3",
					name: "内包装完整、无破损、无漏气"
				},
				{
					id: "4",
					name: "包装支座、垫层牢固无破损"
				},
				{
					id: "5",
					name: "证（章）齐全"
				},
				{
					id: "6",
					name: "签写规范"
				},
				{
					id: "7",
					name: "整洁、保护到位、无损坏"
				},
				{
					id: "8",
					name: "放入指定部位"
				},
				{
					id: "9",
					name: "按工艺要求附带"
				},
				{
					id: "10",
					name: "品种（类）齐全"
				},
				{
					id: "11",
					name: "规格正确"
				},
				{
					id: "12",
					name: "数量准确"
				},
				{
					id: "13",
					name: "无超期"
				},
				{
					id: "14",
					name: "单独包裹放入包装箱指定位置"
				},
				{
					id: "15",
					name: "数量符合要求"
				},
				{
					id: "16",
					name: "放入位置正确"
				},
				{
					id: "17",
					name: "确定箱内无多余物"
				},
				{
					id: "18",
					name: "牢固"
				}
			],
			contentList: [
				{
					id: "1",
					name: "裁制包装纸"
				},
				{
					id: "2",
					name: "裁制包装袋"
				},
				{
					id: "3",
					name: "干燥剂的烘烤和保管"
				},
				{
					id: "4",
					name: "产品外观检查与清洗"
				},
				{
					id: "5",
					name: "制作标签"
				},
				{
					id: "6",
					name: "核对标签 "
				},
				{
					id: "7",
					name: "装袋（包好的产品、干燥剂、指示纸、标签)"
				},
				{
					id: "8",
					name: "封口（包装袋不允许漏气）"
				},
				{
					id: "9",
					name: "装箱（产品、备件、履历本、说明书等）"
				},
				{
					id: "10",
					name: "封箱及铅封"
				},
				{
					id: "11",
					name: "开装箱单"
				},
				{
					id: "12",
					name: "提交"
				}
			],
			edit: false,
			recordsopen: false,
			recordsloading: false,
			recordsList: [],
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			multipleRecords: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 参数表格数据
			configList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				productNumber: undefined,
				productModel: undefined
			},
			// 表单参数
			form: {},
			productList: [],
			productopen: false,
			productloading: false,
			productIds: [],
			recordIds: [],
			recordId: "",
			recordsSection: []
		}
	},
	created() {
		this.getSize()
		this.getworkerList()
		this.getuserDown()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
	this.getSize()
		this.getworkerList()
		this.getuserDown()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Paginationdeliver" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},
		/** 搜索按钮操作 */
		handleQueryUser() {
			this.queryProcuct.pageNum = 1
			this.getrepairProductList()
		},
		/** 重置按钮操作 */
		resetQueryUser() {
			this.resetSelect()
			this.handleQueryUser()
		},
		// 去重
		removeSame1(arr) {
			let map = new Map()
			for (let item of arr) {
				// map.has()方法判断map中是否存在这个键
				// 不存在，则将键和值同时设置到map集合中，
				if (!map.has(item.id)) {
					map.set(item.id, item)
				}
			}
			// 返回map的值
			return [...map.values()]
		},
		setLeft() {
			this.BackSelectionProcuct.forEach(item => {
				this.selectProductList.forEach((items, index) => {
					if (item.id == items.id) {
						this.selectProductList.splice(index, 1)
					}
				})
			})
		},
		setRight() {
			this.selectProductList.push(...this.productIds)
			this.selectProductList = this.removeSame1(this.selectProductList)
			this.$refs.multipleTable.clearSelection()
		},
		handleBackUser(selection) {
			this.BackSelectionProcuct = selection
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		cacheFormChecked() {
			console.log(this.formcheck, "formcheckformcheck")
			this.formcheck.momentFlag = 0
			deliverinstallDeliver(this.formcheck).then(res => {
				this.$modal.msgSuccess("暂存成功")
				this.checkedopen = false
				this.getList()
			})
		},
		submitFormChecked() {
			this.formcheck.momentFlag = 1
			let flag = true
			this.formcheck.tdeliverResultList.forEach(item => {
				if (!item.deliverResult) {
					flag = false
				}
			})
			this.$refs["formcheck"].validate(valid => {
				if (valid) {
					if (flag && this.formcheck.boxOneQuantity && this.formcheck.boxTwoQuantity && this.formcheck.pieceOneQuantity && this.formcheck.pieceTwoQuantity) {
						deliverinstallDeliver(this.formcheck).then(response => {
							this.$modal.msgSuccess("设置成功")
							this.checkedopen = false
							this.getList()
						})
					} else {
						this.$modal.msgError("请先将数据填写完整")
					}
				}
			})
		},
		selectpackagUser(e) {
			this.workLists.forEach(item => {
				if (item.userId == e) {
					this.formcheck.packagUserName = item.nickName
				}
			})
		},
		selectcheckoutUser(e) {
			this.userlist.forEach(item => {
				if (item.userId == e) {
					this.formcheck.checkoutUserName = item.nickName
				}
			})
		},
		getuserDown() {
			allocatedList().then(res => {
				this.userlist = res.rows
			})
		},
		handleChecked(row) {
			this.checkedloading = true
			detailIds(row.id).then(res => {
				this.checkedopen = true
				this.formcheck = res.data
				this.checkedloading = false
			})
		},
		getCurrentDate() {
			let now = new Date()
			let year = now.getFullYear()
			let month = now.getMonth() + 1
			let day = now.getDate()
			return year + "-" + month + "-" + day
		},
		checks() {
			let flag = true
			// this.recordsSection.forEach(item => {
			// 	if (!item.packagRecord || !item.packagUserId) {
			// 		flag = false
			// 	}
			// })
			if (flag) {
				detailsEdits({
					ids: this.recordIds,
					checkoutDate: this.getCurrentDate()
				}).then(res => {
					this.$modal.msgSuccess("核验成功")
					this.recordsopen = false
					this.getdetailList()
					this.getList()
				})
			} else {
				this.$modal.msgError("请先将数据填写完整")
			}
		},
		selectData(row, e) {
			this.workLists.forEach(item => {
				if (item.userId == e) {
					row.packagUserName = item.nickName
					this.editData(row)
				}
			})
		},
		editData(row) {
			detailsEdit(row).then(res => {
				this.$modal.msgSuccess("修改成功")
			})
		},
		handleSelectionRecords(selection) {
			this.recordsSection = selection
			this.recordIds = selection.map(item => item.id)
			this.multipleRecords = !selection.length
		},
		getdetailList() {
			detailList({ packagId: this.recordId }).then(res => {
				this.recordsList = res.rows
			})
		},
		getworkerList() {
			workerList().then(res => {
				this.workLists = res.rows
			})
		},
		submitFormedit() {
			packagedit(this.form).then(res => {
				this.$modal.msgSuccess("修改成功")
				this.edit = false
				this.getList()
			})
		},
		getcontentcheck(row, column, cellValue, index) {
			let labels = ""
			this.checkContentList.forEach(element => {
				if (element.id == row.deliverType) {
					labels = element.name
				}
			})
			return labels
		},
		getcontent(row, column, cellValue, index) {
			let labels = ""
			this.contentList.forEach(element => {
				if (element.id == row.packagType) {
					labels = element.name
				}
			})
			return labels
		},
		getStatus(row, column, cellValue, index) {
			let labels = ""
			this.dict.type.army_state.forEach(element => {
				if (element.value == row.militaryInspectionStatus) {
					labels = element.label
				}
			})
			return labels
		},
		handleSelectionProduct(selection) {
			this.productIds = selection
		},
		/** 查询参数列表 */
		getList() {
			this.loading = true
			deliverList(this.queryParams).then(response => {
				this.configList = response.rows
				this.total = response.total
				this.loading = false
			})
		},
		// 取消按钮
		cancel() {
			this.$refs.multipleTable.clearSelection()
			this.open = false
			this.productIds = []
			this.selectProductList = []
			this.productList = []
		},
		// 表单重置
		reset() {
			this.form = {
				remark: undefined,
				recordName: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.getList()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		getrepairProductList() {
			this.productloading = true
			deliverList1(this.queryProcuct).then(res => {
				this.productList = res.rows
				this.productloading = false
				this.productTotal = res.total
			})
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.resetSelect()
			this.selectProductList = []
			this.productList = []
			this.productIds = []
			this.getrepairProductList()
			this.open = true
			this.title = "添加参数"
		},
		resetSelect() {
			this.queryProcuct = {
				pageNum: 1,
				pageSize: 10,
				recordName: undefined,
				productNumber: undefined
			}
			this.resetForm("queryProcuct")
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length != 1
			this.multiple = !selection.length
		},
		/** 提交按钮 */
		submitForm() {
			if (this.selectProductList.length == 0) {
				this.$modal.msgWarning("请选择产品")
				return
			}

			let ids = []
			this.selectProductList.forEach(item => {
				ids.push(item.id)
			})
			generateDeliver(ids).then(response => {
				this.$modal.msgSuccess("新增成功")
				this.open = false
				this.getList()
			})
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const configIds = row.id || this.ids
			this.$modal
				.confirm("是否确认删除发货数据项？")
				.then(function () {
					return deliverdelete(configIds)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => {})
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"system/config/export",
				{
					...this.queryParams
				},
				`config_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>
<style lang="scss" scoped>
.userDialog {
	display: flex;
	justify-content: space-between;
	align-items: center;
	.userLeft {
		width: 50%;
	}
	.userRight {
		width: 46%;
	}
	.userRight {
		padding-bottom: 5px;
	}
	.userCenter {
		margin: 0 10px;
		> div:first-child {
			margin-bottom: 50px;
		}
		.el-icon-right,
		.el-icon-back {
			font-size: 30px !important;
		}
	}
}
.onerow {
	display: flex;
	align-items: center;
	::v-deep input[type="text"] {
		border: none;
		outline: none;
	}
	> div {
		width: 220px;
		border: 1px solid;
		height: 38px;
		line-height: 36px;
		text-align: center;
		border-right: none;
		// border-top: none;
	}
}
</style>
